﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetriCam;
using MESCodeFile;

namespace mes_tublay
{
    public partial class frmImageCapture : Form
    {
        //Implement MetriCam objects and other attributes
        WebCam cam;
        Timer tmr = new Timer();
        Bitmap bmp = new Bitmap(10, 10);
        bool _hasImage = false, _hasText = false, camReady = true;
        string text = "";
        public frmImageCapture()
        {
            InitializeComponent();
            InitializeForm();
        }
        public void InitializeForm()
        {
            //Instantiate a WebCam object
            btnCapture.Enabled = false;
            cam = new WebCam();
            //Register GUI events.
            DoCamEvents();
            DoGUIEvents();
            //Set the timer interval and enable it.
            tmr.Interval = 10;
            tmr.Enabled = true;
        }
        void DoCamEvents()
        {
            cam.OnConnect += new OnConnectEventHandler(delegate
            {
                btnCapture.Enabled = true;
            });
        }
        //Capture image implementation
        void DoCapture()
        {
            try
            {
                //Check if WebCam is connected, if not, try to connect.
                if (!cam.IsConnected()) cam.Connect();

            }
            catch (Exception)
            {
                Confirm.Error("Imaging Device", "Imaging device not found.\r\nPlease connect a webcam or any image capture device then try again.");
                return;
            }
            //Get the captured image and store it to buffer.
            bmp = cam.GetBitmap();

            //Post Processing
            Graphics g = Graphics.FromImage(bmp);
            //Write text
            if (_hasText)
            {
                float sz = float.Parse(Common.CFG.Read("IMG_FONT_SZ").ToString());

                g.DrawString(text, new Font(Common.CFG.Read("IMG_FONT").ToString(), sz, FontStyle.Bold), Brushes.Black, new PointF(10, bmp.Size.Height - 20));
                g.DrawString(text, new Font(Common.CFG.Read("IMG_FONT").ToString(), sz), Brushes.White, new PointF(10, bmp.Size.Height - 20));
            }
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.Save();
            

            //Set HasTakenImage to true
            _hasImage = true;
            //Disable the timer to prevent further stream to be displayed.
            tmr.Enabled = false;

            //Disconnect the WebCam, the try and catch is due to the bug in MetriCamSDK.
            try
            {
                cam.Disconnect();
            }
            catch (Exception) { }
        }
        //Clean up resources when the form is closed
        void DoCleanUp()
        {
            //Set HasTakenImage to false
            _hasImage = false;
            //Disable the timer to prevent further stream to be displayed.
            tmr.Enabled = false;
            //Disconnect the WebCam, the try and catch is due to the bug in MetriCamSDK.
            try
            {
                cam.Disconnect();
            }
            catch (Exception) { }
            
        }
        //GUI Events
        void DoGUIEvents()
        {
            btnCancel.Click += new EventHandler(delegate
            {
                DoCleanUp();    
                this.Close();
            });
            btnCapture.Click += new EventHandler(delegate
            {
                DoCapture();
                this.Close();
            });
            tmr.Tick += new EventHandler(delegate
            {
                try
                {
                    //Stream live image feedback.
                    if (!cam.IsConnected()) cam.Connect();
                }
                catch (Exception)
                {
                    if (camReady)
                    {
                        camReady = false;
                        Confirm.Error("Imaging Device", "Imaging device not found.\r\nPlease connect a webcam or any image capture device then try again.");
                        return;
                    }
                }
                img.Image = cam.GetBitmap();

            });
           
        }

        //Public members
        /// <summary>
        /// Returns true if the user has taken an image capture.
        /// </summary>
        public bool HasTakenImage
        {
            get { return _hasImage; }
        }
        /// <summary>
        /// Gets the captured image.
        /// </summary>
        /// <returns>Capture image</returns>
        public Bitmap GetImage()
        {
            return bmp;
        }
        /// <summary>
        /// Add a post process text.
        /// </summary>
        /// <param name="txt">Text to add</param>
        public void AddPostProcessText(string txt)
        {
            if (txt.Trim().Length == 0) return;
            _hasText = true;
            text = txt;
        }
        /// <summary>
        /// Use file buffering for taken image.
        /// </summary>
        /// <param name="loc">Directory</param>
        /// <param name="filename">Name of file</param>
        public void SaveToFileBuffer(string loc, string filename)
        {
            if (!System.IO.Directory.Exists(loc)) System.IO.Directory.CreateDirectory(loc);
            bmp.Save(loc + filename);
        }
    }
}
